﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteInEditMode]
public class UICheckboxGroup : MonoBehaviour 
{
	public int mCheckedIndex = -1;
	public List<UICheckbox> childeren = new List<UICheckbox>();
	
	void Start()
	{
		UpdateCheckedIndex();
	}
	
	public int checkedIndex
	{
		get
		{
			if(!finishedUpdateChecked)
				UpdateCheckedIndex();
			
			return mCheckedIndex;
		}
	}
	
	bool finishedUpdateChecked = false;
	public void UpdateCheckedIndex()
	{
		finishedUpdateChecked = true;
		mCheckedIndex = -1;
		childeren.Clear();
		
		UICheckbox[] checkboxs = GetComponentsInChildren<UICheckbox>();
		for(int i = 0; i < checkboxs.Length; i++)
		{
			UICheckbox checkbox = checkboxs[i];
			if(checkbox.radioButtonRoot == transform)
				childeren.Add(checkbox);
		}
		
		for(int i = 0; i < childeren.Count; i++)
		{
			if(childeren[i].isChecked)
			{
				mCheckedIndex = i;
				break;
			}
		}
	}
	
	public void SetCheckedIndex(int index)
	{
		if(index >= childeren.Count || index < 0)
			return;
		
		UICheckbox checkbox = childeren[index];
		if(checkbox != null)
		{
			checkbox.isChecked = true;
			mCheckedIndex = index;
			finishedUpdateChecked = true;
		}
	}
	
	void LateUpdate()
	{
		if(!finishedUpdateChecked)
			UpdateCheckedIndex();
		
		finishedUpdateChecked = false;
	}
}
